import { ActionReducerMapBuilder, AsyncThunk, createAsyncThunk, createSlice, PayloadAction } from "@reduxjs/toolkit";
import { CommentListParams, CommentTotal } from "@/type/CommentType";
import { fetchCommentListAPI, fetchCommentTotalAPI } from "@/api/commentAPI";
import { AsyncThunkConfig } from "@reduxjs/toolkit/dist/createAsyncThunk";
import { Comment } from "@/type/GoodDetailType";


type InitialState = {
   commentTotal: CommentTotal
   commentList: Comment[]
}
const initialState: InitialState = {
   commentTotal: {} as CommentTotal,
   commentList: [],
};


/**
 * @description 获取商品评价总数的AsyncThunk函数
 * */
export const fetchCommentTotalThunk: AsyncThunk<CommentTotal, string, AsyncThunkConfig> = createAsyncThunk("fetchCommentTotalThunk", async (goodsId: string, { rejectWithValue }) => {
   try {
      const { data: { total } } = await fetchCommentTotalAPI(goodsId);
      return total;
   } catch (error: any) {
      return rejectWithValue(error.message);
   }
});

/**
 * @description 获取商品评价列表的AsyncThunk函数
 * */
export const fetchCommentListThunk: AsyncThunk<Comment[], CommentListParams, AsyncThunkConfig> = createAsyncThunk("fetchCommentListThunk", async (params, { rejectWithValue }) => {
   try {
      const { data: { list: { data } } } = await fetchCommentListAPI(params);
      return data;
   } catch (error: any) {
      return rejectWithValue(error.message);
   }
});

const commentStore = createSlice({
   name: "commentStore",
   initialState,
   reducers: {},
   extraReducers(builder: ActionReducerMapBuilder<InitialState>) {
      builder.addCase(fetchCommentTotalThunk.fulfilled, (state: InitialState, action: PayloadAction<CommentTotal>) => {
         state.commentTotal = action.payload;
      });
      builder.addCase(fetchCommentListThunk.fulfilled, (state: InitialState, action: PayloadAction<Comment[]>) => {
       state.commentList=action.payload
      });
   },
});

export default commentStore.reducer;
